<?php
// +----------------------------------------------------------------------
// | 小牛Admin
// +----------------------------------------------------------------------
// | Website: www.xnadmin.cn
// +----------------------------------------------------------------------
// | Author: dav <85168163@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\ArticleClassModel;
use think\facade\View;
use utils\Data;

class ArticleClass extends AdminBase
{
    public function index()
    {
        //分类数据
        $this->assignTree();
        return view();
    }

    /**
     * 编辑分类
     */
    public function edit()
    {
        if( $this->request->isPost() ) {
            $param = $this->request->param();
            $result = ArticleClassModel::update($param);
            if( $result ) {
                xn_add_admin_log('编辑文章分类');
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }
        $id = $this->request->get('id');
        $data = ArticleClassModel::where('id',$id)->find();
        $pid = $data['pid'];
        //分类数据
        $this->assignTree();
        return view('form', compact('data','pid'));
    }

    /**
     * 添加分类
     */
    public function add()
    {
        if( $this->request->isPost() ) {
            $param = $this->request->param();
            $result = ArticleClassModel::create($param);
            if( $result ) {
                xn_add_admin_log('添加文章分类');
                $this->success('操作成功');
            } else {
                $this->success('操作失败');
            }
        }
        $pid = $this->request->get('pid');
        //分类数据
        $this->assignTree();
        return view('form',compact('pid'));
    }

    /**
     * 删除分类
     */
    public function delete()
    {
        $id = intval($this->request->get('id'));
        !($id>0) && $this->error('参数错误');
        $child_count = ArticleClassModel::where('pid',$id)->count();
        $child_count && $this->error('请先删除子节点');
        ArticleClassModel::destroy($id);
        xn_add_admin_log('删除文章分类');
        $this->success('删除成功');
    }

    /**
     * 排序
     */
    public function sort()
    {
        $param = $this->request->post();
        foreach ($param as $k => $v) {
            $v=empty($v) ? null : $v;
            ArticleClassModel::where('id', $k)->save(['sort'=>$v]);
        }
        xn_add_admin_log('排序文章分类');
        $this->success('排序成功', url('index'));
    }

    /**
     * 分类树
     */
    private function assignTree()
    {
        $list = ArticleClassModel::order('sort asc, id asc')->select()->toArray();
        $list = Data::tree($list, 'name','id');
        View::assign('class_list',$list);
    }
}
